package com.framework.myandroid.base

import android.R
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.view.View
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import com.framework.myandroid.MyApplication
import com.framework.myandroid.utils.Constant
import com.framework.myandroid.view.ProgressDialog
import com.framework.myandroid.view.SnackbarUtil
import cxy.com.validate.Validate
import org.greenrobot.eventbus.EventBus
import pub.devrel.easypermissions.EasyPermissions
import java.io.File
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*

abstract class BaseActivity<V, T : BasePresenter<V>?> : AppCompatActivity(), BaseView,
    EasyPermissions.PermissionCallbacks {
    val TAG = "BaseActivity"
    lateinit var myApplication: MyApplication
    protected var mCamareFile: File? = null
    protected var mVideoCameraFile: File? = null
    protected var mPresenter: T? = null
    protected var mBinding: T? = null
    var progressDialog: ProgressDialog? = null
    abstract fun initPresenter(): T
    protected abstract fun setContentView(): Int
    protected abstract fun initData()
    protected abstract fun doOnResume()
    protected abstract fun doOnDestroy()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        mPresenter = initPresenter()
        if (progressDialog == null) {
            progressDialog = ProgressDialog()
        }
        Validate.reg(this)
        myApplication = application as MyApplication
        mBinding = DataBindingUtil.setContentView(this, setContentView());
        initData()
    }

    override fun onResume() {
        super.onResume()
        mPresenter?.attachView(this as V)
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        doOnResume()
    }

    override fun onDestroy() {
        super.onDestroy()
        mPresenter?.detachView()
        Validate.unreg(this)
        EventBus.getDefault().unregister(this)
        doOnDestroy()
    }

    override fun showLoadingDialog() {
        if (progressDialog!!.tag == null) {
            progressDialog!!.show(supportFragmentManager, "progress")
        }
    }

    override fun dismissLoadingDialog() {
        if (progressDialog != null) {
            progressDialog!!.dismiss()
        }
    }

    open fun showShortToast(message: String?) {
        val imm =
            getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm?.hideSoftInputFromWindow(window.decorView.windowToken, 0)
        SnackbarUtil.showBarShortTime(
            findViewById(R.id.content),
            message,
            SnackbarUtil.INFO
        )
    }

    open fun showShortToast(message: String?, type: Int) {
        val imm =
            getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm?.hideSoftInputFromWindow(window.decorView.windowToken, 0)
        SnackbarUtil.showBarShortTime(findViewById(R.id.content), message, type)
    }

    open fun showLongToast(
        message: String?,
        info: String?,
        listener: View.OnClickListener?,
        type: Int
    ) {
        val imm =
            getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm?.hideSoftInputFromWindow(window.decorView.windowToken, 0)
        SnackbarUtil.showBarLongTime(
            findViewById(R.id.content),
            message,
            type,
            info,
            listener
        )
    }

    open fun chooseLocImage() {
        val intent = Intent(Intent.ACTION_GET_CONTENT)
        intent.type = "image/*"
        startActivityForResult(intent, Constant.REQUEST_CODE_IMAGE)
    }

    open fun chooseLocCamera(path: String) {
        val dir =
            File(getExternalFilesDir(null), "${Constant.ACTIVITY_NAME}/$path")
        if (!dir.exists()) {
            dir.mkdirs()
        }
        val df =
            SimpleDateFormat("yyyyMMddHHmmss") //设置日期格式在android中，创建文件时，文件名中不能包含“：”冒号
        val filename = df.format(Date())
        mCamareFile = File(dir, "$filename.png")
        if (!mCamareFile!!.exists()) {
            try {
                mCamareFile!!.createNewFile()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
        selectImageFromCamera(Constant.REQUEST_CODE_CAMERA, mCamareFile)
    }

    open fun selectImageFromCamera(
        requestCode: Int,
        saveImage: File?
    ) {
        var saveImage = saveImage
        if (saveImage == null) {
            saveImage = File(
                getExternalFilesDir(null),
                System.currentTimeMillis().toString() + ".png"
            )
        }
        val currentapiVersion = Build.VERSION.SDK_INT
        val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        if (currentapiVersion < Build.VERSION_CODES.N) {
            intent.action = MediaStore.ACTION_IMAGE_CAPTURE
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(saveImage))
            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1)
        } else {
            if (saveImage.exists()) {
                try {
                    saveImage.createNewFile()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
            val contentValues = ContentValues()
            contentValues.put(MediaStore.Images.Media.DATA, saveImage.absolutePath)
            val uri = contentResolver.insert(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                contentValues
            )
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri)
        }
        startActivityForResult(intent, requestCode)
    }

    override fun requestFailure(t:Throwable) {
        if (t.toString().contains(Constant.TIMEOUT_EXCEPTION)) {
            showShortToast("服务器无响应")
        }
    }
}
